package com.example.wan_android.tools

import android.content.Context
import android.content.SharedPreferences


class Sp private constructor() {
    companion object {
        @Volatile
        private var sharedPrefsInstance: SharedPreferences? = null

        @Synchronized
        fun getSharedPrefs(context: Context): SharedPreferences {
            return sharedPrefsInstance ?: synchronized(Sp::class.java) {
                sharedPrefsInstance ?: context.getSharedPreferences(
                    "wan_android",  // 推荐使用 app 级命名
                    Context.MODE_PRIVATE
                ).also {
                    sharedPrefsInstance = it
                }
            }
        }

        fun setString(context: Context, key: String, value: String) {
            getSharedPrefs(context).edit().putString(key, value).apply()
        }

        fun setBoolean(context: Context, key: String, value: Boolean) {
            getSharedPrefs(context).edit().putBoolean(key, value).apply()
        }


        fun getBoolean(context: Context, key: String, defaultValue: Boolean): Boolean {
            return getSharedPrefs(context).getBoolean(key, defaultValue)
        }

        fun getString(context: Context, key: String, defaultValue: String? = null): String? {
            return getSharedPrefs(context).getString(key, defaultValue)
        }

        fun clear(context: Context) {
            getSharedPrefs(context).edit().clear().apply()
        }
    }


}